import {
	DeleteOutlined,
	DownloadOutlined,
	EditOutlined,
	EyeTwoTone,
	PlusOutlined,
	ReloadOutlined,
	SettingOutlined
} from '@ant-design/icons';
import * as XLSX from 'xlsx';

import type { ActionType, ProColumns } from '@ant-design/pro-components';
import type { MenuProps } from 'antd';

// 基础数据类型
export interface BaseRecord {
	id?: string | number;
	[key: string]: any;
}

// 工具栏配置
export interface ToolBarConfig {
	showAdd?: boolean;
	showExport?: boolean;
	showRefresh?: boolean;
	showSetting?: boolean;
	addText?: string;
	exportText?: string;
	customButtons?: React.ReactNode[];
}

// 批量操作配置
export interface BatchActionConfig {
	showBatchDelete?: boolean;
	showBatchEdit?: boolean;
	customActions?: {
		key: string;
		label: string;
		onClick: (selectedRows: BaseRecord[]) => void;
		danger?: boolean;
	}[];
}

// 表格操作配置
export interface TableActionConfig {
	showEdit?: boolean;
	showDelete?: boolean;
	showView?: boolean;
	customActions?: {
		key: string;
		label: string;
		onClick: (record: BaseRecord) => void;
		danger?: boolean;
	}[];
}

// 主要属性接口
export interface EnhancedProTableProps<T extends BaseRecord = BaseRecord> {
	// ProTable 原有属性
	columns: ProColumns<T>[];
	request?: (
		params: Record<string, any>
	) => Promise<{ data: T[]; success: boolean; total: number }>;
	rowKey?: string | ((record: T) => string);

	// 扩展属性
	toolBar?: ToolBarConfig;
	batchActions?: BatchActionConfig;
	tableActions?: TableActionConfig;

	// 事件回调
	onAdd?: () => void;
	onEdit?: (record: T) => void;
	onDelete?: (record: T) => void;
	onView?: (record: T) => void;
	onBatchDelete?: (selectedRows: T[]) => void;
	onExport?: (data: T[]) => void;

	// 其他配置
	exportFileName?: string;
	showRowSelection?: boolean;
	btnType?: 'space' | 'group';

	// ProTable 的其他属性
	[key: string]: any;
}

const EnhancedProTable = <T extends BaseRecord = BaseRecord>(props: EnhancedProTableProps<T>) => {
	const {
		columns,
		request,
		rowKey = 'id',
		toolBar = {},
		batchActions = {},
		tableActions = {},
		onAdd,
		onEdit,
		onDelete,
		onView,
		onBatchDelete,
		onExport,
		exportFileName = '数据导出',
		showRowSelection = true,
		btnType = 'space',
		...restProps
	} = props;

	const actionRef = useRef<ActionType>();
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [selectedRows, setSelectedRows] = useState<T[]>([]);
	const [loading, setLoading] = useState(false);

	// 刷新表格
	const handleRefresh = useCallback(() => {
		actionRef.current?.reload();
	}, []);

	// 导出数据
	const handleExport = useCallback(async () => {
		if (onExport) {
			onExport(selectedRows.length > 0 ? selectedRows : []);
			return;
		}

		try {
			setLoading(true);

			// 获取当前表格数据
			const tableData = actionRef.current?.getDataSource() ?? [];
			const exportData = selectedRows.length > 0 ? selectedRows : tableData;

			if (exportData.length === 0) {
				window.$message.warning('没有数据可以导出');
				return;
			}

			// 创建工作簿
			const worksheet = XLSX.utils.json_to_sheet(exportData);
			const workbook = XLSX.utils.book_new();
			XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

			// 下载文件
			XLSX.writeFile(workbook, `${exportFileName}.xlsx`);
			window.$message?.success('导出成功');
		} catch (error) {
			window.$message?.error('导出失败');
			console.error('Export error:', error);
		} finally {
			setLoading(false);
		}
	}, [selectedRows, exportFileName, onExport]);

	// 批量删除
	const handleBatchDelete = useCallback(() => {
		if (selectedRows.length === 0) {
			window.$message.warning('请选择要删除的数据');
			return;
		}

		if (onBatchDelete) {
			onBatchDelete(selectedRows);
		}
	}, [selectedRows, onBatchDelete]);

	// 单行操作菜单
	const getActionMenuItems = useCallback(
		(record: T): MenuProps['items'] => {
			const items: MenuProps['items'] = [];

			if (tableActions.showView && onView) {
				items.push({
					key: 'view',
					label: '查看',
					icon: <EyeTwoTone />,
					onClick: () => onView(record)
				});
			}

			if (tableActions.showEdit && onEdit) {
				items.push({
					key: 'edit',
					label: '编辑',
					icon: <EditOutlined />,
					onClick: () => onEdit(record)
				});
			}

			if (tableActions.showDelete && onDelete) {
				items.push({
					key: 'delete',
					label: '删除',
					icon: <DeleteOutlined />,
					danger: true,
					onClick: () => onDelete(record)
				});
			}

			// 自定义操作
			if (tableActions.customActions) {
				tableActions.customActions.forEach(action => {
					items.push({
						key: action.key,
						label: action.label,
						danger: action.danger,
						onClick: () => action.onClick(record)
					});
				});
			}

			return items;
		},
		[tableActions, onView, onEdit, onDelete]
	);

	// 构建最终的列配置
	const finalColumns: ProColumns<T>[] = useMemo(() => {
		const cols = [...columns];

		// 添加操作列
		if (
			tableActions.showEdit ||
			tableActions.showDelete ||
			tableActions.showView ||
			tableActions.customActions?.length
		) {
			cols.push({
				title: '操作',
				dataIndex: 'option',
				valueType: 'option',
				fixed: 'right',
				render: (_, record) => {
					const menuItems = getActionMenuItems(record);

					if (!menuItems || menuItems.length === 0) return null;

					if (menuItems.length === 1) {
						const item = menuItems[0];
						return (
							<AButton type="link" size="small" danger={item.danger} onClick={item.onClick as any}>
								{item.label}
							</AButton>
						);
					}
					if (btnType == 'space') {
						return (
							<ASpace>
								{menuItems.map((item: MenuProps['items'][0]) => (
									<AButton
										key={item.key}
										type="link"
										size="small"
										danger={item.danger}
										onClick={item.onClick as any}
									>
										{item.label}
									</AButton>
								))}
							</ASpace>
						);
					}

					return (
						<ADropdown menu={{ items: menuItems }} trigger={['click']}>
							<AButton type="link" size="small">
								操作 <SettingOutlined />
							</AButton>
						</ADropdown>
					);
				}
			});
		}

		return cols;
	}, [columns, tableActions, getActionMenuItems]);

	// 批量操作菜单
	const batchMenuItems: MenuProps['items'] = useMemo(() => {
		const items: MenuProps['items'] = [];

		if (batchActions.showBatchDelete) {
			items.push({
				key: 'batchDelete',
				label: '批量删除',
				icon: <DeleteOutlined />,
				danger: true,
				onClick: handleBatchDelete
			});
		}

		if (batchActions.customActions) {
			batchActions.customActions.forEach(action => {
				items.push({
					key: action.key,
					label: action.label,
					danger: action.danger,
					onClick: () => action.onClick(selectedRows)
				});
			});
		}

		return items;
	}, [batchActions, selectedRows, handleBatchDelete]);

	return (
		<PProTable<T>
			{...restProps}
			columns={finalColumns}
			request={request}
			rowKey={rowKey}
			actionRef={actionRef}
			loading={loading}
			rowSelection={
				showRowSelection
					? {
							selectedRowKeys,
							onChange: (keys, rows) => {
								setSelectedRowKeys(keys);
								setSelectedRows(rows);
							}
						}
					: false
			}
			headerTitle={selectedRowKeys.length > 0 && <span>已选择 {selectedRowKeys.length} 项</span>}
			toolBarRender={() =>
				[
					// 批量操作
					selectedRowKeys.length > 0 && batchMenuItems.length > 0 && (
						<ADropdown
							key="batch"
							menu={{ items: batchMenuItems }}
							disabled={selectedRowKeys.length === 0}
						>
							<AButton>批量操作 ({selectedRowKeys.length})</AButton>
						</ADropdown>
					),

					// 自定义按钮
					...(toolBar.customButtons || []),

					// 新增按钮
					toolBar.showAdd !== false && onAdd && (
						<AButton key="add" type="primary" icon={<PlusOutlined />} onClick={onAdd}>
							{toolBar.addText || '新建'}
						</AButton>
					),

					// 导出按钮
					toolBar.showExport !== false && (
						<AButton
							key="export"
							icon={<DownloadOutlined />}
							onClick={handleExport}
							loading={loading}
						>
							{toolBar.exportText || '导出'}
						</AButton>
					),

					// 刷新按钮
					toolBar.showRefresh !== false && (
						<AButton key="refresh" icon={<ReloadOutlined />} onClick={handleRefresh}>
							刷新
						</AButton>
					)
				].filter(Boolean)
			}
			pagination={{
				showQuickJumper: true,
				showSizeChanger: true,
				showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`
			}}
			options={{
				setting: toolBar.showSetting !== false,
				fullScreen: true,
				reload: false,
				density: true
			}}
			search={{
				labelWidth: 'auto',
				optionRender: (searchConfig, formProps, dom) => [...dom.reverse()]
			}}
		/>
	);
};

export default EnhancedProTable;
